package com.qingbo.wu.oss.utils;

import com.google.common.collect.Lists;
import com.qingbo.wu.oss.entity.FileInfo;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * minio 文件操作工具
 * @Auther: qingbo.wu
 * @Date: 2024/6/1 16:36
 * @Description:
 */
@Component
public class MinioUtil {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建bucket桶
     * @param bucket
     * @throws Exception
     */
    public void createBucket(String bucket) throws Exception{
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }

    /**
     * 上传文件
     * @param bucket
     * @throws Exception
     */
    public void uploadFile(InputStream inputStream,String bucket,String objectName) throws Exception{
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .stream(inputStream,-1,Integer.MAX_VALUE)
                .build());
    }


    /**
     * 获取所有bucket桶
     * @return
     */
    public List<String> getAllBuckets() throws Exception{
        List<Bucket> bucketList = minioClient.listBuckets();
        return bucketList.stream().map(Bucket::name).collect(Collectors.toList());
    }

    /**
     * 获取当前bucket桶及文件
     * @return
     */
    public List<FileInfo> getAllFile(String bucket) throws Exception{
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucket).build());
        List<FileInfo> fileInfos = Lists.newArrayList();
        for (Result<Item> result : results) {
            Item item = result.get();
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(item.objectName());
            fileInfo.setDirectoryFlag(item.isDir());
            fileInfo.setEtag(item.etag());
        }

        return fileInfos;
    }

    /**
     * 下载文件
     * @param bucket
     * @param objectName
     * @return
     * @throws Exception
     */
    public InputStream downLoad(String bucket,String objectName) throws Exception{
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(objectName).build());
    }

    /**
     * 删除桶
     * @param bucket
     * @throws Exception
     */
    public void deleteBucket(String bucket) throws Exception{
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
    }

    /**
     * 删除文件
     * @param bucket
     * @throws Exception
     */
    public void deleteFile(String bucket,String objectName) throws Exception{
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
    }

}
